#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#




import wsgiref.handlers

import string
import datetime
import StringIO

import friendfeed
import digg
import pylast
import feedparser
import twitter
import gdata
from gdata import service
import atom
try:
  from xml.etree import ElementTree # for Python 2.5 users
except ImportError:
  from elementtree import ElementTree
import gdata.calendar.service
import gdata.alt.appengine
import gdata.youtube
import gdata.youtube.service
import gdata.photos.service
import gdata.media
import gdata.geo
#import flickrapi
import flickr
import getopt

import urllib2

import ljcharm

from google.appengine.ext import webapp
from google.appengine.ext import db

from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.api import urlfetch_errors

class API():
    @staticmethod
    def getYouTubeApi(login, password):
        YOUTUBE_CLIENT_ID = 'YOUTUBE_CLIENT_ID'
        YOUTUBE_DEVELOPER_KEY = 'YOUTUBE_DEVELOPER_KEY'
        YOUTUBE_SOURCE = 'twitteragregator'
        youtubeApi = gdata.youtube.service.YouTubeService()
        gdata.alt.appengine.run_on_appengine(youtubeApi)
        youtubeApi.email = login
        youtubeApi.password = password
        youtubeApi.source = YOUTUBE_SOURCE
        youtubeApi.developer_key = YOUTUBE_DEVELOPER_KEY
        youtubeApi.client_id = YOUTUBE_CLIENT_ID
        youtubeApi.ProgrammaticLogin()
        return youtubeApi
    
    @staticmethod
    def getPicasaApi(login, password):
        gd_client = gdata.photos.service.PhotosService()
        gdata.alt.appengine.run_on_appengine(gd_client)
        gd_client.email = login
        gd_client.password = password
        gd_client.source = 'twitteragregator'
        gd_client.ProgrammaticLogin()
        return gd_client
    
    @staticmethod
    def getBloggerApi(login, password):
        blogger_service = gdata.service.GDataService(login, password)
        gdata.alt.appengine.run_on_appengine(blogger_service)
        blogger_service.source = 'twittagregator'
        blogger_service.service = 'blogger'
        blogger_service.account_type = 'GOOGLE'
        blogger_service.server = 'www.blogger.com'
        blogger_service.ProgrammaticLogin()
        return blogger_service
    
    @staticmethod
    def getGoogleCalendarApi(login, password):
        calendar_service = gdata.calendar.service.CalendarService()
        gdata.alt.appengine.run_on_appengine(calendar_service)
        calendar_service.email = login
        calendar_service.password = password
        calendar_service.source = 'twittagregator'
        calendar_service.ProgrammaticLogin()
        return calendar_service
    
    @staticmethod
    def getLastFMApi(login, password):
        username = login
        md5_password = pylast.md5(password)
        session_key = pylast.SessionKeyGenerator("LASTFM_API_KEY", "LASTFM_SECRET_KEY").get_session_key(username, md5_password)
        user = pylast.User(username, "LASTFM_API_KEYc", "LASTFM_SECRET_KEY", session_key)
        return user
 
    @staticmethod
    def getFriendfeedApi(login, password):
        friendfeedApi = friendfeed.FriendFeed(login, password)
        return friendfeedApi
    
    @staticmethod
    def getDiggApi():
        diggApi = digg.Digg("http%3A%2F%2Ftwittagregator.appspot.com")
        return diggApi
        
    @staticmethod 
    def sendEmailForUser(userInfo, text):
        message = mail.EmailMessage(sender="shami13@gmail.com", subject="Error with autorization, check login")
        message.to = userInfo.user.email()
        message.body = text
        message.send()
    
    @staticmethod 
    def sendRecomendationEmailForUser(userInfo, text):
        message = mail.EmailMessage(sender="shami13@gmail.com", subject="Recomend for registration")
        message.to = userInfo.user.email()
        message.body = text
        message.send()   

class UserInfo(db.Model):
    user = db.UserProperty(required=True)
    sendErrorEmail = db.BooleanProperty()
    twitterLogin = db.EmailProperty()
    twitterPassword = db.StringProperty(default="")
    lastFMLogin = db.StringProperty(default="")
    lastFMPassword = db.StringProperty(default="")
    lastFMNowPlaying = db.StringProperty(default="")
    youtubeLogin = db.StringProperty(default="")
    youtubePassword = db.StringProperty(default="")
    picasaLogin = db.StringProperty(default="")
    picasaPassword = db.StringProperty(default="")
    flickrId = db.StringProperty(default="")
    friendfeedLogin = db.StringProperty(default="")
    friendfeedPassword = db.StringProperty(default="")
    diggLogin = db.StringProperty(default="")
    bloggerLogin = db.StringProperty(default="")
    bloggerPassword = db.StringProperty(default="")
    googleCalendarLogin = db.StringProperty(default="")
    googleCalendarPassword = db.StringProperty(default="")
    
    
class YouTubeContext(db.Model):
    user = db.UserProperty(required=True)
    description = db.StringProperty()
    
class PicasaContext(db.Model):
    user = db.UserProperty(required=True)
    description = db.StringProperty()

class BloggerContext(db.Model):
    user = db.UserProperty(required=True)
    description = db.StringProperty()

class GoogleCalendarContext(db.Model):
    user = db.UserProperty(required=True)
    description = db.StringProperty()


class FlickrContext(db.Model):
    user = db.UserProperty(required=True)
    title = db.StringProperty()

class DiggContext(db.Model):
    user = db.UserProperty(required=True)
    title = db.StringProperty()
    
class FriendfeedContext(db.Model):
    user = db.UserProperty(required=True)
    title = db.StringProperty()    



class MainHandler(webapp.RequestHandler):
 def get(self):
  user = users.get_current_user()
  if user:
      greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" % 
                  (user.nickname(), users.create_logout_url("/")))
      userInfo = UserInfo(user=users.get_current_user())
      user_query = UserInfo.gql('WHERE user = :1', users.get_current_user())
      # Fetch the result from the datastore
      user_result = user_query.fetch(1)
      if user_result:
          userInfo = user_result[0]
      else:
          userInfo.put()
      form = """<form action="/" method="post"> 
                <table>
                <tr>
                <div><td>Twitter Login</td><td><input type="text" name="twitterLogin" value="%s"></td></div> 
                </tr>
                <tr>
                <div><td>Twitter Password</td><td><input type="password" name="twitterPassword" value="%s"></td></div>
                </tr>
                <tr>
                <div><td>YouTube Login(not email)</td><td><input type="text" name="youtubeLogin" value="%s"></td></div> 
                </tr>
                <tr>
                <div><td>YouTube Password</td><td><input type="password" name="youtubePassword" value="%s"></td></div> 
                </tr>
            
                <tr>
                <div><td>Picasa Login</td><td><input type="text" name="picasaLogin" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>Picasa Password</td><td><input type="password" name="picasaPassword" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>Blogger Login</td><td><input type="text" name="bloggerLogin" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>Blogger Password</td><td><input type="password" name="bloggerPassword" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>LastFM Login</td><td><input type="text" name="lastFMLogin" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>LastFM Password</td><td><input type="password" name="lastFMPassword" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>Friendfeed Login</td><td><input type="text" name="friendfeedLogin" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>Friendfeed Api key</td><td><input type="password" name="friendfeedPassword" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>Google Calendar Login</td><td><input type="text" name="googleCalendarLogin" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>Google Calendar Password</td><td><input type="password" name="googleCalendarPassword" value="%s"></td></div> 
                </tr>
                
                
                <tr>
                <div><td>Flickr id(not email)</td><td><input type="text" name="flickrId" value="%s"></td></div> 
                </tr>
                
                <tr>
                <div><td>Digg login(not email)</td><td><input type="text" name="diggLogin" value="%s"></td></div> 
                </tr>
          
                </table>
                <div><input type="submit" value="Save changes"></div>
                </form>""" % (userInfo.twitterLogin, userInfo.twitterPassword,
                              userInfo.youtubeLogin, userInfo.youtubePassword,
                              userInfo.picasaLogin, userInfo.picasaPassword,
                              userInfo.bloggerLogin, userInfo.bloggerPassword,
                              userInfo.lastFMLogin, userInfo.lastFMPassword,
                              userInfo.friendfeedLogin, userInfo.friendfeedPassword,
                              userInfo.googleCalendarLogin, userInfo.googleCalendarPassword,
                              userInfo.flickrId, userInfo.diggLogin)
      greeting = greeting + form
  else:
      self.redirect(users.create_login_url("/"))
      greeting = ("<a href=\"%s\">Sign in or register</a>." % 
                  users.create_login_url("/"))
  self.response.out.write("<html><body>%s</body></html>" % greeting)

 def post(self):
    user = users.get_current_user()
    if user:
      user_query = UserInfo.gql('WHERE user = :1', users.get_current_user())
      # Fetch the result from the datastore
      user_result = user_query.fetch(1)
      if user_result:
          userInfo = user_result[0]
          userInfo.sendErrorEmail = False
          temp = self.request.get('twitterLogin')
          temp1 = self.request.get('twitterPassword')
          
          userInfo.twitterLogin = temp
          userInfo.twitterPassword = temp1
          
          temp = self.request.get('youtubeLogin')
          userInfo.youtubeLogin = temp
          temp = self.request.get('youtubePassword')
          userInfo.youtubePassword = temp
          
          temp = self.request.get('picasaLogin')
          userInfo.picasaLogin = temp
          temp = self.request.get('picasaPassword')
          userInfo.picasaPassword = temp
          
          temp = self.request.get('bloggerLogin')
          userInfo.bloggerLogin = temp
          temp = self.request.get('bloggerPassword')
          userInfo.bloggerPassword = temp
          
          temp = self.request.get('lastFMLogin')
          userInfo.lastFMLogin = temp
          temp = self.request.get('lastFMPassword')
          userInfo.lastFMPassword = temp
          
          temp = self.request.get('friendfeedLogin')
          userInfo.friendfeedLogin = temp
          temp = self.request.get('friendfeedPassword')
          userInfo.friendfeedPassword = temp
          
          temp = self.request.get('googleCalendarLogin')
          userInfo.googleCalendarLogin = temp
          temp = self.request.get('googleCalendarPassword')
          userInfo.googleCalendarPassword = temp
                    
          temp = self.request.get('flickrId')
          userInfo.flickrId = temp
          
          temp = self.request.get('diggLogin')
          userInfo.diggLogin = temp
          
          
          userInfo.put()
    self.redirect("/")

class UpdateHandler(webapp.RequestHandler):
 def get(self):
     userInfos = db.GqlQuery("SELECT * FROM UserInfo")
     for userInfo in userInfos:  
       sendErrorEmail = userInfo.sendErrorEmail  
       twitterApi = twitter.Api(username=userInfo.twitterLogin, password=userInfo.twitterPassword)
       if userInfo.youtubeLogin and userInfo.youtubePassword:  
           try:
               youtubeApi = API.getYouTubeApi(userInfo.youtubeLogin, userInfo.youtubePassword)
           except (gdata.service.BadAuthentication, urlfetch_errors.DownloadError, gdata.service.Error):
               if not sendErrorEmail:
                   userInfo.sendErrorEmail = True
                   API.sendEmailForUser(userInfo, "Wrong login and/or password for YouTube")
           else:          
               try:
                   temp = youtubeApi.GetYouTubeUserFeed(username=userInfo.youtubeLogin)
               except (urlfetch_errors.DownloadError):
                   temp = ""
               else:         
                   lenta = feedparser.parse(StringIO.StringIO(temp))
                   for entity in lenta.entries:
                       youTubeContexts = db.GqlQuery("SELECT * FROM YouTubeContext WHERE user = :1 and description = :2", userInfo.user, entity.title) 
                       flag = True
                       for context in youTubeContexts:
                           flag = False
                           if not flag: break          
                       if flag:
                           youContext = YouTubeContext(user=userInfo.user, description=entity.title)
                           youContext.put()
                           post = "I'm add to youTube video:'%s'" % (youContext.description)
                           if len(post) > 140:
                               post = post[0:139]
                           twitterApi.PostUpdate(post)
       
       if userInfo.picasaLogin and userInfo.picasaPassword:  
           try:
               picasaApi = API.getPicasaApi(userInfo.picasaLogin, userInfo.picasaPassword)
           except (gdata.service.BadAuthentication, gdata.service.CaptchaRequired):
               if not sendErrorEmail:
                   userInfo.sendErrorEmail = True
                   API.sendEmailForUser(userInfo, "Wrong login and/or password for Picasa")
           else:          
               albums = picasaApi.GetUserFeed(user=userInfo.picasaLogin)
               for album in albums.entry:
                   picasaContexts = db.GqlQuery("SELECT * FROM PicasaContext WHERE user = :1 and description = :2", userInfo.user, album.gphoto_id.text) 
                   flag = True
                   for context in picasaContexts:
                       flag = False
                       if not flag: break          
                   if flag:
                       picasaContext = PicasaContext(user=userInfo.user, description=album.gphoto_id.text)
                       picasaContext.put()
                       post = "I'm add to picasa album:'%s'" % (album.title.text)
                       post = unicode(post, 'utf-8')
                       if len(post) > 140:
                           post = post[0:139]
                       twitterApi.PostUpdate(post)
       
       if userInfo.bloggerLogin and userInfo.bloggerPassword:  
           try:
               bloggerApi = API.getBloggerApi(userInfo.bloggerLogin, userInfo.bloggerPassword)
           except (gdata.service.BadAuthentication, gdata.service.CaptchaRequired):
               if not sendErrorEmail:
                   userInfo.sendErrorEmail = True
                   API.sendEmailForUser(userInfo, "Wrong login and/or password for Blogger")
           else:          
              query = service.Query()
              query.feed = '/feeds/default/blogs'
              try: 
               feed = bloggerApi.Get(query.ToUri())
               for entry in feed.entry:
                   bloggerContexts = db.GqlQuery("SELECT * FROM BloggerContext WHERE user = :1 and description = :2", userInfo.user, unicode(entry.title.text, 'utf-8')) 
                   flag = True
                   for context in bloggerContexts:
                       flag = False
                       if not flag: break          
                   if flag:
                       bloggerContext = BloggerContext(user=userInfo.user, description=unicode(entry.title.text, 'utf-8'))
                       bloggerContext.put()
                       post = "I'm add to blogger post:'%s'" % (unicode(entry.title.text, 'utf-8'))
                       if len(post) > 140:
                           post = post[0:139]
                       twitterApi.PostUpdate(post)
              except(gdata.service.RequestError):
                  temp = ''
       if userInfo.googleCalendarLogin and userInfo.googleCalendarPassword:  
         try:  
           try:
               googleCalendarApi = API.getGoogleCalendarApi(userInfo.googleCalendarLogin, userInfo.googleCalendarPassword)
               feed = googleCalendarApi.GetAllCalendarsFeed()
           except (gdata.service.BadAuthentication, gdata.service.CaptchaRequired, urlfetch_errors.DownloadError):
              if not sendErrorEmail:
                   userInfo.sendErrorEmail = True
                   API.sendEmailForUser(userInfo, "Wrong login and/or password for Google Calendar")
           else:   
              
               for i, a_calendar in enumerate(feed.entry):
                   googleCalendarContexts = db.GqlQuery("SELECT * FROM GoogleCalendarContext WHERE user = :1 and description = :2", userInfo.user, a_calendar.title.text) 
                   flag = True
                   
                   for context in googleCalendarContexts:
                       flag = False
                       if not flag: break          
                   if flag:
                       googleCalendarContext = GoogleCalendarContext(user=userInfo.user, description=a_calendar.title.text)
                       googleCalendarContext.put()
                       post = "I'm add to Google Calendar calendar:'%s'" % (a_calendar.title.text)
                       if len(post) > 140:
                           post = post[0:139]
                       twitterApi.PostUpdate(post)
         except(UnicodeDecodeError):
             temp = 'problem'
       
       if userInfo.lastFMLogin and userInfo.lastFMPassword:  
           try:
               lastFMApi = API.getLastFMApi(userInfo.lastFMLogin, userInfo.lastFMPassword)
           except (pylast.ServiceException, urlfetch_errors.DownloadError):
               if not sendErrorEmail:
                   userInfo.sendErrorEmail = True
                   API.sendEmailForUser(userInfo, "Wrong login and/or password for LastFM")
           else:        
               try:
                   trackFM = lastFMApi.get_now_playing()
                   if trackFM is None:
                       tempFM = ""
                   else:
                       tempFM = trackFM.__repr__()
               except (IndexError):
                   tempFM = ""
                   userInfo.lastFMNowPlaying = tempFM
               else:     
                   if tempFM != userInfo.lastFMNowPlaying:
                       userInfo.lastFMNowPlaying = tempFM
                       if tempFM != "":
                        post = "I'm listnening at LastFM '%s'" % (tempFM)
                        if len(post) > 140:
                           post = post[0:139]
                        twitterApi.PostUpdate(post)
               
       if userInfo.friendfeedLogin and userInfo.friendfeedPassword:  
           try:
               friendfeedApi = API.getFriendfeedApi(userInfo.friendfeedLogin, userInfo.friendfeedPassword)
               temp = friendfeedApi.fetch_home_feed()
               feeds = temp['entries']
           except (KeyError):
               if not sendErrorEmail:
                   userInfo.sendErrorEmail = True
                   API.sendEmailForUser(userInfo, "Wrong login and/or app key for Friendfeed")
           else:          
               for entry in feeds:
                   friendfeedContexts = db.GqlQuery("SELECT * FROM FriendfeedContext WHERE user = :1 and description = :2", userInfo.user, entry['id']) 
                   flag = True
                   for context in friendfeedContexts:
                       flag = False
                       if not flag: break          
                   if flag:
                       friendfeedContext = FriendfeedContext(user=userInfo.user, title=entry['id'])
                       friendfeedContext.put()
                       post = "I'm add to Friendfeed post:'%s'" % (entry['title'])
                       if len(post) > 140:
                           post = post[0:139]
                       twitterApi.PostUpdate(post)
                 
                       
       if userInfo.flickrId:        
            try:
                flickUser = flickr.User(id=userInfo.flickrId)
                list = flickUser.getPhotosets()
            except(flickr.FlickrError, urlfetch_errors.DownloadError):
                if not sendErrorEmail:
                   userInfo.sendErrorEmail = True
                   API.sendEmailForUser(userInfo, "Wrong id for Flickr")
            else:
                for set in list:
                    titlePhoto = set.title
                    flickrContexts = db.GqlQuery("SELECT * FROM FlickrContext WHERE user = :1 and title = :2", userInfo.user, titlePhoto) 
                    flag = True
                    for context in flickrContexts:
                        flag = False
                        if not flag: break          
                    if flag:
                        flickrContext = FlickrContext(user=userInfo.user, title=titlePhoto)
                        flickrContext.put()
                        post = "I'm add to flickr photoset:'%s'" % (flickrContext.title)
                        if len(post) > 140:
                            post = post[0:139]
                        twitterApi.PostUpdate(post) 

       if userInfo.diggLogin:        
            try:
                diggApi = API.getDiggApi()
                temp = diggApi.getUserDiggs(userInfo.diggLogin)
            except(urllib2.HTTPError):
                if not sendErrorEmail:
                   userInfo.sendErrorEmail = True
                   API.sendEmailForUser(userInfo, "Wrong login for Digg")
            else:
                for digg in temp:
                    diggContexts = db.GqlQuery("SELECT * FROM DiggContext WHERE user = :1 and title = :2", userInfo.user, digg.story) 
                    flag = True
                    for context in diggContexts:
                        flag = False
                        if not flag: break          
                    if flag:
                        diggContext = DiggContext(user=userInfo.user, tittle=digg.story)
                        diggContext.put()
                        story = diggApi.getStoryByID(digg.story)[0]
                        post = "I'm add digg '%s'" % (story.title)
                        if len(post) > 140:
                            post = post[0:139]
                        twitterApi.PostUpdate(post) 

       userInfo.put()

class BayesHandler(webapp.RequestHandler):
 def get(self):
     from pybayes.Examples import dog, sprinkler, learndog
     sprinkler.run()

class LearningHandler(webapp.RequestHandler):
 def get(self):
     from pybayes.Models.bn import DBN
     from pybayes.DataStructures.randomvariables import RandomVariable
     from pybayes.Learning.learning import ParameterLearner
     name = "userinfos"
     header = \
     """    The User Info Network\n """

     T = RandomVariable('twitter',["True","False"])
     G = RandomVariable('google',["True","False"])
     M = RandomVariable('media',["True", "False"])
     P = RandomVariable('photo',["True", "False"])
     B = RandomVariable('blog',["True", "False"])
     LF = RandomVariable('lastfm',["True", "False"])
     YT = RandomVariable('youtube',["True", "False"])
     GC = RandomVariable('googlecalendar',["True", "False"])
     DG = RandomVariable('digg',["True", "False"])
     FF = RandomVariable('friendfeed',["True", "False"])
     BG = RandomVariable('blogger',["True", "False"])
     PS = RandomVariable('picasa',["True", "False"])
     FK = RandomVariable('flickr',["True", "False"])
     
     ### Graph Nodes
     V = [T,G,M,P,B,LF,YT,GC,DG,FF,BG,PS,FK]
     ### Graph Arcs
     E = [(T,G), (T,M), (T,P), (T,B),
          (M,YT), (M,LF),
          (P,PS), (P,FK),
          (B,GC), (B,BG), (B,DG), (B,FF),
          (G,GC), (G,YT), (G,PS), (G,BG)
          ]
     
     ### Bayesian network
     g = DBN(V,E,name,header)
     dat = []
     userInfos = db.GqlQuery("SELECT * FROM UserInfo")
     for userInfo in userInfos:
         if userInfo.twitterLogin and userInfo.twitterPassword:
             twitter = True
         else: 
             twitter = False    
         if userInfo.youtubeLogin and userInfo.youtubePassword:
             youtube = True
         else:
             youtube = False    
         if userInfo.picasaLogin and userInfo.picasaPassword:
             picasa = True
         else:
             picasa = False    
         if userInfo.bloggerLogin and userInfo.bloggerPassword:
             blogger = True
         else:
             blogger = False  
         if userInfo.lastFMLogin and userInfo.lastFMPassword:
             lastfm = True
         else:
             lastfm = False
         if userInfo.flickrId != "":
             flickr = True
         else:
             flickr = False
         if userInfo.friendfeedLogin and userInfo.friendfeedPassword:
             friendfeed = True
         else:
             friendfeed = False    
         if userInfo.diggLogin != "":
             digg = True
         else:
             digg = False
         if userInfo.googleCalendarLogin and userInfo.googleCalendarPassword:
             googlecalendar = True
         else:
             googlecalendar = False
         if not userInfo.sendErrorEmail:
             entry = []
             if twitter:
                 entry.append("True")
             else: 
                 entry.append("False")
             if youtube or picasa or blogger or googlecalendar:
                 entry.append("True")
             else: 
                 entry.append("False")
             if youtube or picasa or lastfm or flickr:
                 entry.append("True")
             else: 
                 entry.append("False")    
             if picasa or flickr:
                 entry.append("True")
             else: 
                 entry.append("False")   
             if blogger or friendfeed or googlecalendar or digg:
                 entry.append("True")
             else: 
                 entry.append("False")      
             if lastfm:
                 entry.append("True")
             else: 
                 entry.append("False")
             if youtube:
                 entry.append("True")
             else: 
                 entry.append("False")      
             if googlecalendar:
                 entry.append("True")
             else: 
                 entry.append("False")   
             if digg:
                 entry.append("True")
             else: 
                 entry.append("False")
             if friendfeed:
                 entry.append("True")
             else: 
                 entry.append("False")
             if blogger:
                 entry.append("True")
             else: 
                 entry.append("False")  
             if picasa:
                 entry.append("True")
             else: 
                 entry.append("False")
             if flickr:
                 entry.append("True")
             else: 
                 entry.append("False")
             dat.append(entry)
     if len(dat)>0:   
      learner = ParameterLearner(g,dat,V)
      learner.learn(0.001) 
      for userInfo in userInfos:
         if userInfo.twitterLogin and userInfo.twitterPassword:
             twitter = True
         else: 
             twitter = False    
         if userInfo.youtubeLogin and userInfo.youtubePassword:
             youtube = True
         else:
             youtube = False    
         if userInfo.picasaLogin and userInfo.picasaPassword:
             picasa = True
         else:
             picasa = False    
         if userInfo.bloggerLogin and userInfo.bloggerPassword:
             blogger = True
         else:
             blogger = False  
         if userInfo.lastFMLogin and userInfo.lastFMPassword:
             lastfm = True
         else:
             lastfm = False
         if userInfo.flickrId != "":
             flickr = True
         else:
             flickr = False
         if userInfo.friendfeedLogin and userInfo.friendfeedPassword:
             friendfeed = True
         else:
             friendfeed = False    
         if userInfo.diggLogin != "":
             digg = True
         else:
             digg = False
         if userInfo.googleCalendarLogin and userInfo.googleCalendarPassword:
             googlecalendar = True
         else:
             googlecalendar = False
         prohibites = {}
         if not twitter:
             evidences = {}
             queries = {}
             evidences = {T: 'True'}
             queries[YT] = youtube
             queries[PS] = picasa
             queries[BG] = blogger
             queries[LF] = lastfm
             queries[FK] = flickr
             queries[FF] = friendfeed
             queries[DG] = digg
             queries[GC] = googlecalendar
             prohibites[T] = g.inference(queries,evidences)
         if not youtube:
             evidences = {}
             queries = {}
             evidences = {YT: 'True'}
             queries[T] = twitter
             queries[PS] = picasa
             queries[BG] = blogger
             queries[LF] = lastfm
             queries[FK] = flickr
             queries[FF] = friendfeed
             queries[DG] = digg
             queries[GC] = googlecalendar
             prohibites[YT] = g.inference(queries,evidences)    
         if not picasa:
             evidences = {}
             queries = {}             
             evidences = {PS: 'True'}
             queries[T] = twitter
             queries[YT] = youtube
             queries[BG] = blogger
             queries[LF] = lastfm
             queries[FK] = flickr
             queries[FF] = friendfeed
             queries[DG] = digg
             queries[GC] = googlecalendar
             prohibites[PS] = g.inference(queries,evidences)     
         if not blogger:
             evidences = {}
             queries = {}             
             evidences = {BG: 'True'}
             queries[T] = twitter
             queries[PS] = picasa
             queries[YT] = youtube
             queries[LF] = lastfm
             queries[FK] = flickr
             queries[FF] = friendfeed
             queries[DG] = digg
             queries[GC] = googlecalendar
             prohibites[BG] = g.inference(queries,evidences) 
         if not lastfm:
             evidences = {}
             queries = {}             
             evidences = {LF: 'True'}
             queries[T] = twitter
             queries[PS] = picasa
             queries[BG] = blogger
             queries[YT] = youtube
             queries[FK] = flickr
             queries[FF] = friendfeed
             queries[DG] = digg
             queries[GC] = googlecalendar
             prohibites[LF] = g.inference(queries,evidences)   
         if not flickr:
             evidences = {}
             queries = {}             
             evidences = {FK: 'True'}
             queries[T] = twitter
             queries[PS] = picasa
             queries[BG] = blogger
             queries[LF] = lastfm
             queries[YT] = youtube
             queries[FF] = friendfeed
             queries[DG] = digg
             queries[GC] = googlecalendar
             prohibites[FK] = g.inference(queries,evidences) 
         if not friendfeed:
             evidences = {}
             queries = {}             
             evidences = {FF: 'True'}
             queries[T] = twitter
             queries[PS] = picasa
             queries[BG] = blogger
             queries[LF] = lastfm
             queries[YT] = youtube
             queries[FF] = friendfeed
             queries[DG] = digg
             queries[GC] = googlecalendar
             prohibites[FF] = g.inference(queries,evidences)   
         if not digg:
             evidences = {}
             queries = {}             
             evidences = {DG: 'True'}
             queries[T] = twitter
             queries[PS] = picasa
             queries[BG] = blogger
             queries[LF] = lastfm
             queries[FK] = flickr
             queries[FF] = friendfeed
             queries[YT] = youtube
             queries[GC] = googlecalendar
             prohibites[DG] = g.inference(queries,evidences) 
         if not googlecalendar:
             evidences = {}
             queries = {}             
             evidences = {GC: 'True'}
             queries[T] = twitter
             queries[PS] = picasa
             queries[BG] = blogger
             queries[LF] = lastfm
             queries[FK] = flickr
             queries[FF] = friendfeed
             queries[DG] = digg
             queries[YT] = youtube
             prohibites[GC] = g.inference(queries,evidences)
         if len(prohibites) > 0:
             maxKey = prohibites.keys()[0]
             maxProhibit  = prohibites.values()[0]
             for key, val in prohibites.items():
                 if val > maxProhibit:
                     maxKey = key
                     maxProhibit = val   
             text = "We recommend that you register at "    
             if maxKey == GC:
                 text = text + "Google Calendar"
             elif maxKey == YT:
                 text = text + "YouTube"
             elif maxKey == FK:
                 text = text + "Flikr"        
             elif maxKey == PS:
                 text = text + "Picasa"   
             elif maxKey == LF:
                 text = text + "LastFM"  
             elif maxKey == FF:
                 text = text + "Friendfeed"
             elif maxKey == T:
                 text = text + "Twitter"       
             elif maxKey == BG:
                 text = text + "Blogger"         
             elif maxKey == DG:
                 text = text + "Digg"   
             API.sendRecomendationEmailForUser(userInfo, text)
              

def main():
  application = webapp.WSGIApplication([('/', MainHandler),
                                        ('/update', UpdateHandler),
                                        ('/bayes', BayesHandler),
                                        ('/learn', LearningHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
  
  

